package com.ray.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.poi.util.ArrayUtil;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.fasterxml.jackson.databind.PropertyNamingStrategy.KebabCaseStrategy;
import com.google.appengine.repackaged.org.joda.time.DateTime;
import com.ray.bean.CompanyMaterialCountBean;
import com.ray.bean.CompanyMaterialTableBean;
import com.ray.bean.CompanyMaterialTypeBean;
import com.ray.bean.CustomerBean;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.DepartmentBean;
import com.ray.bean.DuplicateOrderUpdateRecordBean;
import com.ray.bean.FeedOrderMainBean;
import com.ray.bean.MaterialBean;
import com.ray.bean.OrderInfoDetailBean;
import com.ray.bean.PersonBean;
import com.ray.bean.ProcessBean;
import com.ray.bean.SalaryRelatedOperationsRecordBean;
import com.ray.bean.UserBean;
import com.ray.bean.WarehouseInOutDetailBean;
import com.ray.bean.WorkshopProductionCycleBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.BasicDataMapper;
import com.ray.mapper.CompanyMaterialMapper;
import com.ray.mapper.DingTalkMapper;
import com.ray.mapper.DuplicateOrderUpdateRecordsMapper;
import com.ray.mapper.OrderMapper;
import com.ray.pojo.AttendDevicePojo;
import com.ray.pojo.BaseProcessDetailPojo;
import com.ray.pojo.MyUser;
import com.ray.pojo.UserDeptWorkPojo;
import com.ray.util.ArrayUtils;
import com.ray.util.ConfigUtil;
import com.ray.util.DingTalkUtil;
import com.ray.util.GUID;
import com.ray.util.ResponseUtil;
import com.ray.util.ReturnStringUtil;
import com.ray.util.StringUtil;
import com.ray.util.TimeAndUnix;
import com.ray.util.baidu.BaiduSimilarPicSearchUtils;
import com.ray.util.baidu.Brief;
import com.ray.util.baidu.Tags;
import com.ray.util.callback.CallBackBody;
import com.ray.util.callback.CallBackTask;
import com.ray.util.qiniu.QiniuExtraUrlParamUtils;
import com.ray.util.redis.RedisCache;
import com.ray.util.weixin.WeixinTemplateSender;
import com.sun.mail.util.BEncoderStream;

import net.sf.json.JSONArray;
import net.sourceforge.pinyin4j.PinyinHelper;

@Service
public class BasicDataService {
	@Autowired
	BasicDataMapper basicDataMapper;
	@Autowired
	OrderProcedureTemplateService orderProcedureTemplateService;
	@Autowired
	OrderService orderService;
	@Autowired
	CompanyMaterialMapper companyMaterialMapper;
	@Autowired
	OrderMapper orderMapper;
	@Autowired
	CompanyMaterialCountService companyMaterialCountService;
	@Autowired
	CompanyMaterialService companyMaterialService;
	@Autowired
	UserService userService;
	@Autowired
	DingTalkMapper dingTalkMapper;
	@Autowired
	StructureTreeService structureTreeService;
	@Autowired
	DingTalkService dingTalkService;
	@Autowired
	WorkshopService workshopService;
	@Autowired
	CompanyMaterialTypeService companyMaterialTypeService;
	@Autowired
	DuplicateOrderUpdateRecordsService duplicateOrderUpdateRecordsService;
	@Autowired
	DuplicateOrderUpdateRecordsMapper duplicateOrderUpdateRecordsMapper;
	@Autowired
	AttendanceService attendanceService;
	@Autowired
	WarehouseService warehouseService;
	@Autowired
	ShoppingMallService shoppingMallService;

	// 周期修改
	public void updateCycle(Map<String, Object> map) throws ServiceException {
		map.put("lastModifier", map.get("loginUserName").toString());
		List<WorkshopProductionCycleBean> workList = workshopService.getWorkshopProductionDetail(map);
		Assert.isTrue(workList != null && workList.size() > 0, "该车间不存在");
		basicDataMapper.updateCycle(map);
	}

	/**
	 * 添加数据到车间生产周期表,并添加交接出入库工序
	 * 
	 * @param workshopProductionCycleBean
	 * @param myuser
	 * @throws ServiceException
	 * @author 王荣
	 */
	public void insertCycle(Map<String, Object> map) throws ServiceException {
		// 检查车间是否重复
		List<WorkshopProductionCycleBean> list = basicDataMapper.checkWorkshopIsRepeat(map);
		if (list != null && list.size() > 0) {
			throw new ServiceException("车间已存在");
		}
		Double processCycle = map.get("processCycle").toString().isEmpty() ? null
				: Double.valueOf(map.get("processCycle").toString());
		Double dailyCapacity = map.get("dailyCapacity").toString().isEmpty() ? null
				: Double.valueOf(map.get("dailyCapacity").toString());
		map.put("processCycle", processCycle);
		map.put("dailyCapacity", dailyCapacity);
		// 根据生产线名称获取生产线id
		basicDataMapper.insertCycle(map);
		// 插入工序：交接出入库
		basicDataMapper.insertHandoverProcess(map);
	}

	/**
	 * @author wangrong
	 * @param map
	 * @return
	 */
	public List<BaseProcessDetailPojo> getProcessDetail(Map<String, Object> map) {
		return basicDataMapper.getProcessDetail(map);
	}

	public List<PersonBean> getDeptManagerList(MyUser myuser) {
		String company = myuser.getCompany();
		return basicDataMapper.getDeptManagerList(company);
	}

	// 公司物料表
	// 查询所有物料
	public DatatablesViewPageBean<CompanyMaterialTableBean> queryMaterialCompany(Map map) {
		int count = 0;
		DatatablesViewPageBean<CompanyMaterialTableBean> dvpb = new DatatablesViewPageBean<CompanyMaterialTableBean>();
		count = basicDataMapper.queryMaterialCompanyCount(map);
		dvpb.setReturnData(basicDataMapper.queryMaterialCompany(map));
		dvpb.setiTotalDisplayRecords(count);
		dvpb.setiTotalRecords(count);
		return dvpb;
	}
	//查询物料是否使用
	public int queryMaterialCompanyIsUsed(Map map) {
		// TODO Auto-generated method stub
		return basicDataMapper.queryMaterialCompanyIsUsed(map);
	}

	// 获取公司物料详情
	public List<CompanyMaterialTableBean> getCompanyMaterialDetail(Map map) {
		List<CompanyMaterialTableBean> materialDetail = basicDataMapper.getCompanyMaterialDetail(map);
		return materialDetail;
	}

	// 公共物料表
	// 查询所有物料
	public DatatablesViewPageBean<MaterialBean> queryMaterial(Map map) {
		int count = 0;
		DatatablesViewPageBean<MaterialBean> dvpb = new DatatablesViewPageBean<MaterialBean>();
		count = basicDataMapper.queryMaterialCount(map);
		dvpb.setReturnData(basicDataMapper.queryMaterial(map));
		dvpb.setiTotalDisplayRecords(count);
		dvpb.setiTotalRecords(count);
		return dvpb;
	}

	// 获取物料详情
	public List<MaterialBean> getMaterialDetail(Map map) {
		List<MaterialBean> materialDetail = basicDataMapper.getMaterialDetail(map);
		return materialDetail;
	}

	// 获取物料代码
	public List<String> getMaterialCode() {
		return basicDataMapper.getMaterialCode();
	}

	// 获取公司物料代码
	public List<CompanyMaterialTableBean> getCompanyMaterialCode(Map map) {
		return basicDataMapper.getCompanyMaterialCode2(map);
	}

	// 根据物料代码获取物料名称
	public List<String> getMaterialNameByCode(String materialCode) {
		return basicDataMapper.getMaterialNameByCode(materialCode);
	}

	// 获取物料名称
	public List<String> getMaterialName() {
		return basicDataMapper.getMaterialName();
	}

	// 获取公司物料名称
	public List<String> getCompanyMaterialName(Map map) {
		return basicDataMapper.getCompanyMaterialName(map);
	}

	// 获取规格型号
	public List<String> getModel() {
		return basicDataMapper.getModel();
	}

	// 获取公司物料表规格型号
	public List<String> getCompanyModel(Map map) {
		return basicDataMapper.getCompanyModel(map);
	}

	// 获取单位
	public List<String> getUnit() {
		return basicDataMapper.getUnit();
	}

	// 获取公司单位
	public List<String> getCompanyUnit(Map map) {
		return basicDataMapper.getCompanyUnit(map);
	}

	// 获取默认仓库
	public List<String> getDefaultWarehouse() {
		return basicDataMapper.getDefaultWarehouse();
	}

	// 获取公司默认仓库
	public List<String> getCompanyDefaultWarehouse(Map map) {
		return basicDataMapper.getCompanyDefaultWarehouse(map);
	}

	// 获取供应商名称
	public List<String> getProviderName() {
		return basicDataMapper.getProviderName();
	}

	// 获取公司供应商名称
	public List<String> getCompanyProviderName(Map map) {
		return basicDataMapper.getCompanyProviderName(map);
	}

	// 获取物料类型
	public List<String> getMaterialType() {
		return basicDataMapper.getMaterialType();
	}

	// 获取公司物料类型
	public List<String> getCompanyMaterialType(Map map) {
		return basicDataMapper.getCompanyMaterialType(map);
	}

	// 获取色号
	public List<String> getColor() {
		return basicDataMapper.getColor();
	}

	// 获取公司色号
	public List<String> getCompanyColor(Map map) {
		return basicDataMapper.getCompanyColor(map);
	}

	// 根据色号获取色号描述
	public List<String> getColorDescription(String color) {
		return basicDataMapper.getColorDescription(color);
	}

	// 根据色号获取公司物料表色号描述
	public List<String> getCompanyColorDescription(Map map) {
		System.out.println("Companycolor:" + map.get("color"));
		return basicDataMapper.getCompanyColorDescription(map);
	}

	// 修改物料
	public void updateMaterial(MaterialBean materialBean, MyUser myuser) {
		// 获取当前时间，并转换为字符串
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String dateString = sdf.format(new Date());
		// 设置最后修改时间
		materialBean.setLastModifyTime(dateString);
		// 设置最后修改人
		materialBean.setLastModifier(myuser.getUserName());
		basicDataMapper.updateMaterial(materialBean);
	}
	
	// 批量修改物料是否为现货属性
	public void updateCompanyMaterialIsSpot(CompanyMaterialTableBean materialBean, MyUser myuser) {
		// 获取当前时间，并转换为字符串
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String dateString = sdf.format(new Date());
		// 设置最后修改时间
		materialBean.setLastModifyTime(dateString);
		// 设置最后修改人
		materialBean.setLastModifier(myuser.getUserName());
		materialBean.setCompany(myuser.getCompany());
		basicDataMapper.updateCompanyMaterialIsSpot(materialBean);
	}
	// 批量修改公司物料信息是否显示
	public void updateCompanyMaterialConfig(CompanyMaterialTableBean materialBean, MyUser myuser) {
		// 获取当前时间，并转换为字符串
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String dateString = sdf.format(new Date());
		// 设置最后修改时间
		materialBean.setLastModifyTime(dateString);
		// 设置最后修改人
		materialBean.setLastModifier(myuser.getUserName());
		materialBean.setCompany(myuser.getCompany());
		basicDataMapper.updateCompanyMaterialConfig(materialBean);
	}

	// 修改物料
	public void updateCompanyMaterial(CompanyMaterialTableBean materialBean, MyUser myuser) throws Exception {
		// 获取当前时间，并转换为字符串
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String dateString = sdf.format(new Date());
		// 设置最后修改时间
		materialBean.setLastModifyTime(dateString);
		// 设置最后修改人
		materialBean.setLastModifier(myuser.getUserName());
		materialBean.setCompany(myuser.getCompany());
		Map<String, Object> unitMap = new HashMap<String, Object>();
		unitMap.put("color", materialBean.getColor().trim());
		unitMap.put("loginCompany", myuser.getCompany());
		unitMap.put("materialName", materialBean.getMaterialName().trim());
		unitMap.put("providerName", materialBean.getProviderName().trim());
		unitMap.put("model", materialBean.getModel().trim());
		unitMap.put("materialDeptId", materialBean.getMaterialDeptId());
		List<CompanyMaterialTableBean> companyDatalist = basicDataMapper.getUniqueCompanyMaterialByDetail(unitMap);
		for (CompanyMaterialTableBean companyMaterialTableBean : companyDatalist) {
			if (companyMaterialTableBean.getId().equals(materialBean.getId())) {
				companyDatalist.remove(companyMaterialTableBean);
				break;
			}
		}
		if (materialBean.getStatus().equals("使用")) {
			if (companyDatalist.size() > 0) {
				throw new ServiceException("已经有相同的物料正在使用,该物料信息无法更新");
			}
		} else if (materialBean.getStatus().equals("禁用")) {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("id", materialBean.getId());
			List<CompanyMaterialTableBean> list = basicDataMapper.getCompanyMaterialDetail(paramMap);
			CompanyMaterialTableBean companyMaterialTableBean = list.get(0);
			paramMap.put("companyMaterialTableBean", companyMaterialTableBean);
			paramMap.put("loginCompany", myuser.getCompany());
			this.isCount(paramMap);
		}
		basicDataMapper.updateCompanyMaterial(materialBean);
		//同步更新商城
		shoppingMallService.updateMaterialFromCompanyMaterial(materialBean, myuser);
		//异步同步到百度图片库
		synImgsToBaidu(materialBean, myuser,"0");
	}

	// 插入物料
	public void insertMaterial(MaterialBean materialBean, MyUser myuser) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String dateString = sdf.format(new Date());
		materialBean.setCreationTime(dateString);
		materialBean.setLastModifyTime(dateString);
		materialBean.setCreater(myuser.getUserName());
		materialBean.setLastModifier(myuser.getUserName());
		// 设置排序号
		int sortKey = basicDataMapper.getMaxSortFromMaterialTable() + 1;
		materialBean.setSortKey(sortKey);
		// 设置物料代码 供应商-物料类型-日期+编号（0001）
		String materialCode = setMaterialCode(materialBean.getProviderName(), materialBean.getMaterialName());
		materialBean.setMaterialCode(materialCode);
		// 添加
		basicDataMapper.insertMaterial(materialBean);

	}

	/**
	 * 
	 * Title: insertCompanyMaterial Description: 向公司物料表中插入数据
	 * 
	 * @return 返回插入物料的id的对象
	 * @param materialBean
	 * @param myuser
	 * @author 王荣
	 * @throws ServiceException
	 * @date 2018年4月12日 下午1:51:35
	 */
	public List<CompanyMaterialTableBean> insertCompanyMaterial(CompanyMaterialTableBean materialBean, MyUser myuser)
			throws ServiceException {
		List<CompanyMaterialTableBean> resultData = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String dateString = sdf.format(new Date());
		Map<String, Object> unitMap = new HashMap<String, Object>();
		int isReadColor = 1;
		// 校验该物料类型是否需要颜色
//		if("原材料仓".equals(materialBean.getDefaultWarehouse())) {
//			Map<String, String> mateiralTypeMap = new HashMap<String, String>();
//			mateiralTypeMap.put("loginCompany", myuser.getCompany());
//			mateiralTypeMap.put("materialType", materialBean.getMaterialType());
//			mateiralTypeMap.put("status", "1");
//			CompanyMaterialTypeBean materialTreeBean = companyMaterialTypeService
//					.getCompanyMaterialTypeByMateiralType(mateiralTypeMap);
//			if (materialTreeBean != null) {
//				isReadColor = materialTreeBean.getIsReadColor();
//			}
//		}else {
//			isReadColor = 2; 
//		}
		Map<String, String> mateiralTypeMap = new HashMap<String, String>();
		mateiralTypeMap.put("loginCompany", myuser.getCompany());
		mateiralTypeMap.put("materialType", materialBean.getMaterialType());
		mateiralTypeMap.put("status", "1");
		CompanyMaterialTypeBean materialTreeBean = companyMaterialTypeService
				.getCompanyMaterialTypeByMateiralType(mateiralTypeMap);
		if (materialTreeBean != null) {
			isReadColor = materialTreeBean.getIsReadColor();
		}
		//不再判断是否读取颜色描述
		/*if (isReadColor == 2) {
			materialBean.setColor("");
			materialBean.setColorDescription("");
			unitMap.put("color", "");
		} else {
			Assert.isTrue(materialBean.getColor()!=null && !"".equals(materialBean.getColor().trim()), "读颜色的物料.色号不能为空");
			unitMap.put("color", materialBean.getColor().trim());
		}*/
		unitMap.put("color", materialBean.getColor().trim());
		
		unitMap.put("loginCompany", myuser.getCompany());
		unitMap.put("materialName", materialBean.getMaterialName().trim());
		unitMap.put("providerName", materialBean.getProviderName().trim());
		unitMap.put("model", materialBean.getModel().trim());
		unitMap.put("materialDeptId", materialBean.getMaterialDeptId());
		// 校验物料信息是否存在
		checkMaterialIsExist(unitMap);
		materialBean.setCreationTime(dateString);
		materialBean.setLastModifyTime(dateString);
		materialBean.setCreater(myuser.getUserName());
		materialBean.setLastModifier(myuser.getUserName());
		materialBean.setCompany(myuser.getCompany());
		// 设置物料代码
		String materialCode = setCompanyMaterialCode(materialBean.getProviderName(), materialBean.getMaterialName());
		materialBean.setMaterialCode(materialCode);
		resultData = basicDataMapper.insertCompanyMaterial(materialBean);
		unitMap.put("companyMaterialTableBean", materialBean);
		this.addCompanyMaterialCountOnMaterial(unitMap);
		//异步同步到百度图片库
		synImgsToBaidu(materialBean,myuser,"0");
		return resultData;
	}
	
	@Transactional(propagation=Propagation.REQUIRES_NEW)
	public List<CompanyMaterialTableBean> insertCompanyMaterialShoppingTest(CompanyMaterialTableBean materialBean, MyUser myuser)
			throws ServiceException {
		List<CompanyMaterialTableBean> resultData = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String dateString = sdf.format(new Date());
		Map<String, Object> unitMap = new HashMap<String, Object>();
		int isReadColor = 1;
		// 校验该物料类型是否需要颜色
//		if("原材料仓".equals(materialBean.getDefaultWarehouse())) {
//			Map<String, String> mateiralTypeMap = new HashMap<String, String>();
//			mateiralTypeMap.put("loginCompany", myuser.getCompany());
//			mateiralTypeMap.put("materialType", materialBean.getMaterialType());
//			mateiralTypeMap.put("status", "1");
//			CompanyMaterialTypeBean materialTreeBean = companyMaterialTypeService
//					.getCompanyMaterialTypeByMateiralType(mateiralTypeMap);
//			if (materialTreeBean != null) {
//				isReadColor = materialTreeBean.getIsReadColor();
//			}
//		}else {
//			isReadColor = 2; 
//		}
//		Map<String, String> mateiralTypeMap = new HashMap<String, String>();
//		mateiralTypeMap.put("loginCompany", myuser.getCompany());
//		mateiralTypeMap.put("materialType", materialBean.getMaterialType());
//		mateiralTypeMap.put("status", "1");
//		CompanyMaterialTypeBean materialTreeBean = companyMaterialTypeService
//				.getCompanyMaterialTypeByMateiralType(mateiralTypeMap);
//		if (materialTreeBean != null) {
//			isReadColor = materialTreeBean.getIsReadColor();
//		}
//		if (isReadColor == 2) {
//			materialBean.setColor("");
//			materialBean.setColorDescription("");
//			unitMap.put("color", "");
//		} else {
//			Assert.isTrue(materialBean.getColor()!=null && !"".equals(materialBean.getColor().trim()), "读颜色的物料.色号不能为空");
//			unitMap.put("color", materialBean.getColor().trim());
//		}
		unitMap.put("loginCompany", myuser.getCompany());
		unitMap.put("materialName", materialBean.getMaterialName().trim());
		unitMap.put("color", materialBean.getColor().trim());
		unitMap.put("providerName", materialBean.getProviderName().trim());
		unitMap.put("model", materialBean.getModel().trim());
		unitMap.put("materialDeptId", materialBean.getMaterialDeptId());
		// 校验物料信息是否存在
		checkMaterialIsExist(unitMap);
		materialBean.setCreationTime(dateString);
		materialBean.setLastModifyTime(dateString);
		materialBean.setCreater(myuser.getUserName());
		materialBean.setLastModifier(myuser.getUserName());
		materialBean.setCompany(myuser.getCompany());
		// 设置物料代码
		String materialCode = setCompanyMaterialCode(materialBean.getProviderName(), materialBean.getMaterialName());
		materialBean.setMaterialCode(materialCode);
		resultData = basicDataMapper.insertCompanyMaterial(materialBean);
		unitMap.put("companyMaterialTableBean", materialBean);
		this.addCompanyMaterialCountOnMaterial(unitMap);
		//异步同步到百度图片库
		synImgsToBaidu(materialBean,myuser,"0");
		return resultData;
	}
	/**
	 * 物料表导入图片 
	 * @param bean
	 * @param myuser
	 * @param tag 0:不分类 1板料 2眼镜圈 3眼镜腿 4商城
	 */
	public void synImgsToBaidu(CompanyMaterialTableBean bean,MyUser myuser,String tag) {
		Object context = "上下文信息";
		 
        new CallBackTask(new CallBackBody() {
            @Override
			public
            void execute(Object context) throws Exception {
               
               delSynImgsToBaiduCheckRedis("conpanyMaterialTable:"+bean.getId()+":img");
               delSynImgsToBaiduCheckRedis("conpanyMaterialTable:"+bean.getId()+":imgTwo");
               delSynImgsToBaiduCheckRedis("conpanyMaterialTable:"+bean.getId()+":imgThree");
               delSynImgsToBaiduCheckRedis("conpanyMaterialTable:"+bean.getId()+":imgFour");
               
               if(!"".equals(bean.getImg())&&null!=bean.getImg()) {
            	    com.alibaba.fastjson.JSONObject remark = new com.alibaba.fastjson.JSONObject();
            	    remark.put("id", bean.getId());
            	    remark.put("img", bean.getImg());
            	    
            	   	Brief brief = new Brief("", bean.getMaterialCode(),"",myuser.getCompanyId(),remark.toJSONString());
           			JSONObject object = BaiduSimilarPicSearchUtils.similarPicInsertForRemote(brief, Tags.getSameTag(tag, myuser.getCompanyId()), QiniuExtraUrlParamUtils.waterMakerText(bean.getImg(), myuser.getCompany()+bean.getMaterialCode()+GUID.getGuid(), "仿宋", "580", "#5C2727", "100", null, null, null));
           			if(!object.has("error_code"))addSynImgsToBaiduCheckRedis("conpanyMaterialTable:"+bean.getId()+":img", object);
               }
               if(!"".equals(bean.getImgTwo())&&null!=bean.getImg()) {
            	   	com.alibaba.fastjson.JSONObject remark = new com.alibaba.fastjson.JSONObject();
	           	    remark.put("id", bean.getId());
	           	    remark.put("img", bean.getImgTwo());
	           	    
	           	   	Brief brief = new Brief("", bean.getMaterialCode(),"",myuser.getCompanyId(),remark.toJSONString());
            	    JSONObject object =BaiduSimilarPicSearchUtils.similarPicInsertForRemote(brief, Tags.getSameTag(tag, myuser.getCompanyId()), QiniuExtraUrlParamUtils.waterMakerText(bean.getImgTwo(), myuser.getCompany()+bean.getMaterialCode()+GUID.getGuid(), "仿宋", "580", "#5C2727", "100", null, null, null));   
            	    if(!object.has("error_code"))addSynImgsToBaiduCheckRedis("conpanyMaterialTable:"+bean.getId()+":imgTwo", object);
               }
               if(!"".equals(bean.getImgThree())&&null!=bean.getImg()) {
            	    com.alibaba.fastjson.JSONObject remark = new com.alibaba.fastjson.JSONObject();
           	        remark.put("id", bean.getId());
           	        remark.put("img", bean.getImgThree());
           	        
           	        Brief brief = new Brief("", bean.getMaterialCode(),"",myuser.getCompanyId(),remark.toJSONString());
            	    JSONObject object =BaiduSimilarPicSearchUtils.similarPicInsertForRemote(brief, Tags.getSameTag(tag, myuser.getCompanyId()), QiniuExtraUrlParamUtils.waterMakerText(bean.getImgThree(), myuser.getCompany()+bean.getMaterialCode()+GUID.getGuid(), "仿宋", "580", "#5C2727", "100", null, null, null));
            	    if(!object.has("error_code"))addSynImgsToBaiduCheckRedis("conpanyMaterialTable:"+bean.getId()+":imgThree", object);
               }
               if(!"".equals(bean.getImgFour())&&null!=bean.getImg()) {
            	    com.alibaba.fastjson.JSONObject remark = new com.alibaba.fastjson.JSONObject();
          	        remark.put("id", bean.getId());
          	        remark.put("img", bean.getImgFour());
          	        Brief brief = new Brief("", bean.getMaterialCode(),"",myuser.getCompanyId(),remark.toJSONString());
          	        
            	    JSONObject object =BaiduSimilarPicSearchUtils.similarPicInsertForRemote(brief, Tags.getSameTag(tag, myuser.getCompanyId()), QiniuExtraUrlParamUtils.waterMakerText(bean.getImgFour(), myuser.getCompany()+bean.getMaterialCode()+GUID.getGuid(), "仿宋", "580", "#5C2727", "100", null, null, null));
            	    if(!object.has("error_code"))addSynImgsToBaiduCheckRedis("conpanyMaterialTable:"+bean.getId()+":imgFour", object);
               }

            }
 
            public void onSuccess(Object context) {
               
            }
 
            public void onFailure(Object context) {
               
            }
        }).start(context);
	}
	//上传成功将cont_sign增加到redis
	public void addSynImgsToBaiduCheckRedis(String key,JSONObject object) {
		if(!object.has("error_code")) {
			RedisCache.setDataToRedis(key, object.get("cont_sign"), null);
		}
	}
		
	//redis中获取cont_sign 删除百度图库的图片并将redis 缓存删除
	public void delSynImgsToBaiduCheckRedis(String key) {
		String contSign = (String) RedisCache.getDataFromRedis(key);
		if(contSign!=null&&contSign.length()>0) {
			BaiduSimilarPicSearchUtils.similarPicDeleteForRemoteByContSign(contSign);
			RedisCache.delKey(key);
		}
	}
	
	
	/**
	 * 插入物料信息
	 * @param materialTableBean
	 */
	public void insertCompanyMaterial(CompanyMaterialTableBean materialTableBean) {
		basicDataMapper.insertCompanyMaterial(materialTableBean);
	}
	
	/**
	 * 
	 * Title: setMaterialCode Description: 设置'公共'物料表的物料代码
	 * 
	 * @param providerName
	 *            供应商名称
	 * @param MaterialName
	 *            原物料类型 现改为 ‘物料名称’
	 * @return
	 * @author 王荣
	 * @date 2018年4月10日 下午2:39:37
	 */
	public String setMaterialCode(String providerName, String MaterialName) {
		String gongyingshang = getPYIndexStr(providerName, true);
		String wuliaoleixing = getPYIndexStr(MaterialName, true);
		SimpleDateFormat rq = new SimpleDateFormat("yyyyMMdd");
		String rqString = rq.format(new Date());
		List<String> datalist = basicDataMapper.getMaterialCode();
		// 标识位
		Boolean flag = false;
		for (String i : datalist) {//
			if (i.contains(rqString)) {
				flag = true;
				break;
			}
		}
		if (flag) {
			// 如果物料代码包含今天日期，则最大+1
			String str = basicDataMapper.getMaxMaterialCode();
			// 获取最后4位数
			int number = Integer.valueOf(str.substring(str.length() - 4, str.length()));
			StringBuilder sb = new StringBuilder();
			sb.append(str);
			sb.replace(0, sb.indexOf("-"), gongyingshang);
			sb.replace(sb.indexOf("-") + 1, sb.lastIndexOf("-"), wuliaoleixing);
			sb.replace(sb.length() - String.valueOf(number + 1).length(), sb.length(), String.valueOf(number + 1));
			return sb.toString();
		} else {
			// 如果数据库中物料代码不包含今天日期，则0001
			return gongyingshang + "-" + wuliaoleixing + "-" + rqString + "0001";
		}
	}

	/**
	 * 
	 * Title: setCompanyMaterialCode Description: 设置'公司'物料表的物料代码
	 * 
	 * @param providerName
	 *            供应商名称
	 * @param MaterialName
	 *            原物料类型 现改为 ‘物料名称’
	 * @return
	 * @author 王荣
	 * @date 2018年4月10日 下午2:39:04
	 */
	public String setCompanyMaterialCode(String providerName, String MaterialName) {
		String gongyingshang = getPYIndexStr(providerName, true);
		String wuliaoleixing = getPYIndexStr(MaterialName, true);
		SimpleDateFormat rq = new SimpleDateFormat("yyyyMMdd");
		String rqString = rq.format(new Date());
		// 判断物料代码中是否包含今天的日期
		List<String> datalist = basicDataMapper.getCompanyMaterialCode(rqString);

		if (datalist != null && datalist.size() > 0) {
			// 如果物料代码包含今天日期，则最大+1
			String str = basicDataMapper.getMaxCompanyMaterialCode(rqString);
			// 获取最后4位数
			int number = Integer.valueOf(str.substring(str.length() - 4, str.length()));
			StringBuilder sb = new StringBuilder();
			sb.append(str);
			sb.replace(0, sb.indexOf("-"), gongyingshang);
			sb.replace(sb.indexOf("-") + 1, sb.lastIndexOf("-"), wuliaoleixing);
			sb.replace(sb.length() - String.valueOf(number + 1).length(), sb.length(), String.valueOf(number + 1));
			System.out.println("sbToString:" + sb.toString());
			return sb.toString();
		} else {
			// 如果数据库中物料代码不包含今天日期，则0001
			return gongyingshang + "-" + wuliaoleixing + "-" + rqString + "0001";
		}
	}

	// 根据公司名称获取公司id
	public int getCompanyId(String company) {
		return basicDataMapper.getCompanyId(company);
	}

	// 用户表相关
	// 查询全部职员
	public DatatablesViewPageBean<PersonBean> queryPersonnel(Map<String, Object> map) {
		int count = 0;
		String[] searchText = map.get("searchText") == null ? null : map.get("searchText").toString().split("\\s+");
		map.put("searchText", searchText);
		DatatablesViewPageBean<PersonBean> dtcpb = new DatatablesViewPageBean<PersonBean>();
		count = basicDataMapper.queryPersonnelCount(map);
		dtcpb.setReturnData(count > 0 ? basicDataMapper.queryPersonnel(map) : new ArrayList<PersonBean>());
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}
	/**
	 * 通过搜索条件获取公司职员简单信息
	 * @param requestMap
	 * @author 王荣
	 */
	public List<UserDeptWorkPojo> getUserSimpleInfo(Map<String, Object> requestMap){
		/* 根据空格分隔得到多搜索条件 */
		String[] searchText = requestMap.get("searchText") == null ? null : requestMap.get("searchText").toString().split("\\s+");
		requestMap.put("searchText", searchText);
		return basicDataMapper.getUserSimpleInfo(requestMap);
	}
	// 根据部门名称获取职员
	public List<PersonBean> getPersonName(Map map) {
		return basicDataMapper.getPersonName(map);
	}

	// 获取职员详情
	public List<PersonBean> getPersonDetail(String id) {
		List<PersonBean> personDetail = basicDataMapper.getPersonDetail(id);
		return personDetail;
	}
	/**
	 * 第一代体温识别新增用户
	 * @param userId
	 * @param equipment
	 * @return
	 */
	public String sendMsgToLowerHairUserToEquipmentForAdd(String userId , String equipment) {
		ConfigUtil.setPropertiesName("db.properties");
		ConfigUtil.init();
		String lowerHairUserToEquipmentUrl=ConfigUtil.getValue("dk.lowerHairUserToEquipment");
		System.out.println("准备开始执行异步任务...");
	    final Object context = "上下文信息";
	 
        new CallBackTask(new CallBackBody() {
            @Override
			public
            void execute(Object context) throws Exception {
                System.out.println("\n正在执行耗时操作...");
                System.out.println(context);
                Thread.sleep(1000);
        		WeixinTemplateSender.httpRequest(lowerHairUserToEquipmentUrl+"/api/v1/record/lowerHairUserToEquipment?userId="+userId+"&equipmentNo="+equipment, "GET", null);
                System.out.println("\n执行完成！");
            }
 
            public void onSuccess(Object context) {
                System.out.println("\n成功后的回调函数...");
                System.out.println(context);
            }
 
            public void onFailure(Object context) {
                System.out.println("\n失败后的回调函数...");
                System.out.println(context);
            }
	      }).start(context);
		 System.out.println("\n异步任务已经开始，请等待完成...");
		return null;
	}
	/**
	 *  第一代体温识别删除用户
	 * @param map
	 * @throws ServiceException
	 */
	public String sendMsgToLowerHairUserToEquipmentForDelete(String userId , List<AttendDevicePojo> devicePojos) {
		ConfigUtil.setPropertiesName("db.properties");
		ConfigUtil.init();
		String lowerHairUserToEquipmentUrl=ConfigUtil.getValue("dk.lowerHairUserToEquipment");
		System.out.println("准备开始执行异步任务...");
	    final Object context = "上下文信息";
	    
        new CallBackTask(new CallBackBody() {
            @Override
			public
            void execute(Object context) throws Exception {
                System.out.println("\n正在执行耗时操作...");
                System.out.println(context);
                for (AttendDevicePojo attendDevicePojo : devicePojos) {
                	if (attendDevicePojo.getDeviceType().equals(2)) {
                		WeixinTemplateSender.httpRequest(lowerHairUserToEquipmentUrl+"/api/v1/record/deleteUserToEquipment?userId="+userId+"&equipmentNo="+attendDevicePojo.getDeviceId(), "GET", null);
					}
				}
                System.out.println("\n执行完成！");
            }
 
            public void onSuccess(Object context) {
                System.out.println("\n成功后的回调函数...");
                System.out.println(context);
            }
 
            public void onFailure(Object context) {
                System.out.println("\n失败后的回调函数...");
                System.out.println(context);
            }
	      }).start(context);
		 System.out.println("\n异步任务已经开始，请等待完成...");
		return null;
	}
	// update职员
	@SuppressWarnings("unchecked")
	public void updatePerson(Map<String, Object> map) throws ServiceException {
		String duty = map.get("duty").toString();
		String userName = map.get("personName").toString();
		String personId = map.get("personId").toString();
		String company = map.get("loginCompany").toString();
		
		String attendDeviceId = map.get("attendDeviceId") == null ? "[]" : map.get("attendDeviceId").toString();
		List<Integer> deviceIdList = DingTalkUtil.jsonStrToList(attendDeviceId, Integer.class);
		
		String attendDeviceType = map.get("attendDeviceType") == null ? "[]" : map.get("attendDeviceType").toString();
		List<Integer> deviceTypeList = DingTalkUtil.jsonStrToList(attendDeviceType, Integer.class);
		
		String attendDeviceNo = map.get("attendDeviceNo") == null ? "[]" : map.get("attendDeviceNo").toString();
		List<String> deviceNoList = DingTalkUtil.jsonStrToList(attendDeviceNo, String.class);
		
		if (deviceIdList.size()!=deviceTypeList.size()) {
			throw new ServiceException("考勤机ID和Type数量不匹配");
		}
		if (deviceIdList.size()!=deviceNoList.size()) {
			throw new ServiceException("考勤机ID和deviceNo数量不匹配");
		}
		if ("开启".equals(map.get("status"))
				&& !userService.checkUser(userName, map.get("phoneNumber").toString(), personId, company)) {
			throw new ServiceException("用户名或手机号重复");
		}
		String deptId = map.get("deptId").toString();
		if ("开启".equals(map.get("status"))) {
			if ("1".equals(duty)) {
				String deptDuty = basicDataMapper.getDeptDuty(deptId, personId, company);
				if (deptDuty != null && deptDuty.length() > 0) {
					throw new ServiceException("该部门已设置了经理，如要跟换经理，请先取消原经理职务");
				}
			} else if ("2".equals(duty)) {
				String workshopDuty = basicDataMapper.getWorkshopDuty(map);
				if (workshopDuty != null && workshopDuty.length() > 0) {
					throw new ServiceException("该车间已设置了主管，如要跟换主管，请先取消原主管职务");
				}
			}
			/* 不为禁用时判断是否修改考勤机，添加考勤机增减人员指令 */ 
			//多考勤机类型
			/*for(int i = 0 ; i<deviceTypeList.size();i++) {
				if(deviceTypeList.get(i).equals(1)) {//第一代指纹打卡 新增
					List<Integer> list = new ArrayList<>();
					list.add(deviceIdList.get(i));
					dingTalkService.insertDeviceTrans(list, personId, userName);
				}
				if(deviceTypeList.get(i).equals(2)) {//第一代体温打卡 新增
					userService.lowerHairUserToEquipment(personId, deviceNoList.get(i));
				}
			}*/
		}else {
			//禁用时 删除所有考勤机中的此人
			//多考勤机类型
			/*for(int i = 0 ; i<deviceTypeList.size();i++) {
				if(deviceTypeList.get(i).equals(1)) {//第一代指纹打卡 禁用
					dingTalkService.insertDeviceTrans(personId);
				}
				if(deviceTypeList.get(i).equals(2)) {//第一代体温打卡 禁用
					
				}
			}*/
		}
		String currentDateStr = new DateTime().toString("yyyy-MM-dd");
		String effectiveStartDate = null;
		if (map.get("effectiveDateArr") != null) {// 表示有修改工资相关的数据
			String effectiveDateStr = map.get("effectiveDateArr").toString();
			net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(effectiveDateStr);
			List<Map<String, Object>> list = jsonArray.subList(0, jsonArray.size());
			List<SalaryRelatedOperationsRecordBean> newList = new ArrayList<SalaryRelatedOperationsRecordBean>();
			//当前日期
			for (int i = 0; i < list.size(); i++) {
				SalaryRelatedOperationsRecordBean bean = new SalaryRelatedOperationsRecordBean();
				Map<String, Object> m = (Map<String, Object>) list.get(i);
				String effectiveDate = m.get("effectiveDate") == null ? currentDateStr : m.get("effectiveDate").toString();
				String fieldName = m.get("fieldName").toString();
				String previousValue = m.get("previousValue").toString();
				String modifiedValue = m.get("modifiedValue").toString();
				bean.setTableName("用户表");
				bean.setEffectiveDate(effectiveDate);
				bean.setFieldName(fieldName);
				bean.setPreviousValue(previousValue);
				bean.setModifiedValue(modifiedValue);
				int state = 1;
				// 如果生效日期比今天晚，就设置字段值为修改之前的值，到生效日期后，再修改值为修改之后的值
				if (TimeAndUnix.compareDate(currentDateStr, "yyyy-MM-dd", effectiveDate, "yyyy-MM-dd") > 0) {
					map.put(fieldName, previousValue);
					state = 0;
				}else {//立即生效时
					if("monthlySalary".equals(fieldName)) {
						//标志修改工资生效起始日期
						effectiveStartDate = effectiveDate;
					}
				}
				bean.setState(state);
				newList.add(bean);
			}
			map.put("effectiveDateArr", newList);
			basicDataMapper.operationSalaryRelatedRecord(map);
		}
		basicDataMapper.updatePerson(map);
		//多考勤机类型
		//获取所有这个人相关卡机
		List<AttendDevicePojo> sourceDeviceList = dingTalkMapper.selectAttendDeviceListByUserId(personId);
		sendMsgToLowerHairUserToEquipmentForDelete(personId,sourceDeviceList);//删除一代体温考勤机设备人员
		if ("开启".equals(map.get("status"))) {
			/* 不为禁用时判断是否修改考勤机，添加考勤机增减人员指令 */ 
			//多考勤机类型
			dingTalkService.insertDeviceTrans(deviceIdList, personId, userName);
			for(int i = 0 ; i<deviceTypeList.size();i++) {
				if(deviceTypeList.get(i).equals(1)) {//第一代指纹打卡 新增
					
				}
				if(deviceTypeList.get(i).equals(2)) {//第一代体温打卡 新增
					sendMsgToLowerHairUserToEquipmentForAdd(personId, deviceNoList.get(i));
				}
			}
		}else {
			//禁用时 删除所有考勤机中的此人
			//多考勤机类型
			dingTalkService.insertDeviceTrans(personId);
			for(int i = 0 ; i<deviceTypeList.size();i++) {
				if(deviceTypeList.get(i).equals(1)) {//第一代指纹打卡 禁用
					
				}
				if(deviceTypeList.get(i).equals(2)) {//第一代体温打卡 禁用
					
				}
			}
		}
		//如果skills为空则设为"[]"
		String skills = map.computeIfAbsent("skills", k -> "[]").toString();
		List<Map<String, Object>> skillList = DingTalkUtil.jsonStrToList(skills, Map.class);
		if(skillList.size()>0) {
			map.put("skillList", skillList);
			/* 修改用户技能 */
			basicDataMapper.updateUserSkill(map);
		}
		if(effectiveStartDate!=null) {
			//修改工资，重新计算生效日期后的每日工资详情
			attendanceService.updateDailySalaryRecord(effectiveStartDate, currentDateStr, company, Integer.valueOf(personId), null);
		}
	}

	public void insertPerson(PersonBean personBean, Map<String, Object> map) throws ServiceException {
		String personName = personBean.getPersonName();
		String phone = personBean.getPhoneNumber();
		String company = map.get("loginCompany").toString();
		if (!userService.checkUser(personName, phone, "", company)) {
			throw new ServiceException("用户名或手机号重复");
		}
		String deptId = basicDataMapper.getDeptId(personBean.getDeptName(), company);
		Map<String, Object> newmap = new HashMap<String, Object>();
		newmap.put("deptId", deptId);
		newmap.put("workshopId", personBean.getWorkshopID());
		newmap.put("personId", personBean.getPersonId());
		newmap.put("userName", personName);
		newmap.put("company", company);
		String duty = personBean.getDuty();
		if ("1".equals(duty)) {
			String deptDuty = basicDataMapper.getDeptDuty(deptId, personBean.getPersonName(), company);
			if (deptDuty != null && deptDuty.length() > 0) {
				throw new ServiceException("该部门已设置了经理，如要跟换经理，请先取消原经理职务");
			}
		} else if ("2".equals(duty)) {
			String workshopDuty = basicDataMapper.getWorkshopDuty(newmap);
			if (workshopDuty != null && workshopDuty.length() > 0) {
				throw new ServiceException("该车间已设置了主管，如要跟换主管，请先取消原主管职务");
			}
		}
		personBean.setCreater(map.get("loginUserName").toString());
		personBean.setCompany(company);
		// 设置排序号
		int sortKey = basicDataMapper.getMaxSortFromPerson() + 1;
		personBean.setSortKey(sortKey);
		// 根据部门名称获取部门id
		personBean.setDeptName(basicDataMapper.getDeptId(personBean.getDeptName(), company));
		// 设置默认密码为123
		personBean.setPassword("123");

		basicDataMapper.insertPerson(personBean);// 添加成功后会返回一个id personBean.getId()获取
		
		String attendDeviceId = map.get("attendDeviceId") == null ? "[]" : map.get("attendDeviceId").toString();
		@SuppressWarnings("unchecked")
		List<Integer> deviceIdList = DingTalkUtil.jsonStrToList(attendDeviceId, Integer.class);
		
		String attendDeviceType = map.get("attendDeviceType") == null ? "[]" : map.get("attendDeviceType").toString();
		@SuppressWarnings("unchecked")
		List<Integer> deviceTypeList = DingTalkUtil.jsonStrToList(attendDeviceType, Integer.class);
		
		String attendDeviceNo = map.get("attendDeviceNo") == null ? "[]" : map.get("attendDeviceNo").toString();
		@SuppressWarnings("unchecked")
		List<String> deviceNoList = DingTalkUtil.jsonStrToList(attendDeviceNo, String.class);
		
		if (deviceIdList.size()!=deviceTypeList.size()) {
			throw new ServiceException("考勤机ID和Type数量不匹配");
		}
		if (deviceIdList.size()!=deviceNoList.size()) {
			throw new ServiceException("考勤机ID和deviceNo数量不匹配");
		}
		if(deviceIdList.size()>0) {
			//多考勤机类型
			dingTalkService.insertDeviceTrans(deviceIdList, personBean.getId().toString(), personName);
			for(int i = 0 ; i<deviceTypeList.size();i++) {
				if(deviceTypeList.get(i).equals(1)) {//第一代指纹打卡
					
				}
				if(deviceTypeList.get(i).equals(2)) {//第一代体温打卡
					//userService.lowerHairUserToEquipment(personBean.getId().toString(), deviceNoList.get(i));
					sendMsgToLowerHairUserToEquipmentForAdd(personBean.getId().toString(), deviceNoList.get(i));
				}
			}
			
		}
		
		String skills = map.get("skills") == null ? "[]" : map.get("skills").toString();
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> skillList = DingTalkUtil.jsonStrToList(skills, Map.class);
		if(skillList.size()>0) {
			map.put("personId", personBean.getId());
			map.put("skillList", skillList);
			basicDataMapper.updateUserSkill(map);
		}
	}

	/*
	 * 部门表相关
	 */	
	public DatatablesViewPageBean<DepartmentBean> queryDept(Map map) {
		int count = 0;
		DatatablesViewPageBean<DepartmentBean> dtcpb = new DatatablesViewPageBean<DepartmentBean>();
		count = basicDataMapper.queryDeptCount(map);
		dtcpb.setReturnData(basicDataMapper.queryDept(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	// 获取部门名称
	public List<DepartmentBean> getDeptName(Map map) {
		return basicDataMapper.getDeptName(map);
	}

	// 获取部门详情
	public List<DepartmentBean> getDeptDetail(String deptName, String company, String view) {
		List<DepartmentBean> deptDetail = basicDataMapper.getDeptDetail(deptName, company, view);
		return deptDetail;
	}

	// update部门表
	public void updateDept(DepartmentBean departmentBean, Map map) throws ServiceException {
		// 对比部门是否存在
		departmentBean.setCompany(String.valueOf(map.get("loginCompany")));
		if (!departmentBean.getStatus().equals("禁用")) {
			List<DepartmentBean> list = basicDataMapper.compareDept(departmentBean);
			if (list != null && list.size() > 0) {
				throw new ServiceException("该部门已存在");
			}
		}
		departmentBean.setLastModifier(map.get("loginUserName").toString());
		basicDataMapper.updateDept(departmentBean);
	}

	// insert部门表
	public void insertDept(DepartmentBean departmentBean, MyUser myuser) throws ServiceException {
		// 检查部门名称是否重复
		departmentBean.setCompany(myuser.getCompany());
		List<DepartmentBean> list = basicDataMapper.getDeptDetail(departmentBean.getDeptName(), myuser.getCompany(),
				"1");
		if (list != null && list.size() > 0) {
			throw new ServiceException("该部门已存在");
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String dateString = sdf.format(new Date());
		// 设置time
		departmentBean.setCreationTime(dateString);
		departmentBean.setLastModifyTime(dateString);
		// 设置排序号
		int sortKey = basicDataMapper.getMaxSortFromDept() + 1;
		departmentBean.setSortKey(sortKey);
		// 设置name
		departmentBean.setUserName(myuser.getUserName());
		departmentBean.setCreater(myuser.getUserName());
		departmentBean.setLastModifier(myuser.getUserName());
		basicDataMapper.insertDept(departmentBean);
	}

	// 客户表相关
	// 查询所有客户
	public DatatablesViewPageBean<CustomerBean> queryCustomers(Map<String, Object> map) throws ServiceException {
		int count = 0;
		DatatablesViewPageBean<CustomerBean> dtcpb = new DatatablesViewPageBean<CustomerBean>();
		count = basicDataMapper.queryCustomersCount(map);
		dtcpb.setReturnData(basicDataMapper.queryCustomers(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	/**
	 * 
	 * Title: getCustomerCode Description: TODO(这里用一句话描述这个方法的作用)
	 * 
	 * @param map
	 * @return
	 * @author 王荣
	 * @date 2018年4月19日 下午1:54:09
	 */
	public List<CustomerBean> getCustomerCode(Map map) {
		return basicDataMapper.getCustomerCode(map);
	}
	
	/**
	 * 
	 * Title: getCustomerCode Description: TODO(这里用一句话描述这个方法的作用)
	 * 
	 * @param map
	 * @return
	 * @author 王荣
	 * @date 2018年4月19日 下午1:54:09
	 */
	public List<CustomerBean> getCustomerSubCode(Map map) {
		return basicDataMapper.getCustomerSubCode(map);
	}

	// 获取客户名称
	public List<CustomerBean> getCustomerName(Map map) {
		return basicDataMapper.getCustomerName(map);
	}

	// 获取客户详情
	public List<CustomerBean> getCustomerDetail(Map map) {
		List<CustomerBean> customerDetail = basicDataMapper.getCustomerDetail(map);
		return customerDetail;
	}

	// 修改客户信息
	public void updateCustomer(Map map) throws ParseException {
		if (!map.get("status").equals("禁用")) {
			List<CustomerBean> list = basicDataMapper.compareCustomer(map);
			if (list != null && list.size() > 0) {
				throw new ServiceException("该客户代码或客户名称已存在");
			}
		}
		basicDataMapper.updateCustomer(map);
	}
	
	// 修改客户信息
	public void updateCustomerSub(Map map) throws ParseException {
		if (!map.get("status").equals("禁用")) {
			List<CustomerBean> list = basicDataMapper.compareCustomerSub(map);
			if (list != null && list.size() > 0) {
				throw new ServiceException("该客户代码或客户名称已存在");
			}
		}
		basicDataMapper.updateCustomerSub(map);
	}
	
	// 修改客户信息 只为linkCompany
	public int updateCustomerForLinkCompany(Map map)  {
		return basicDataMapper.updateCustomerForLinkCompany(map);
	}

	// 插入客户信息
	public void insertCustomer(CustomerBean customerBean, MyUser myuser) throws ServiceException {
		Map<String, String> map = new HashMap<String, String>();
		map.put("loginCompany", myuser.getCompany());
		map.put("customerCode", customerBean.getCustomerCode());
		map.put("customerName", customerBean.getCustomerName());
		map.put("id", customerBean.getId());
		List<CustomerBean> list = basicDataMapper.compareCustomer(map);
		if (list != null && list.size() > 0) {
			throw new ServiceException(ReturnStringUtil.CUSTOMER_ALERADY_HAVE_ECEPTION);
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String dateString = sdf.format(new Date());
		customerBean.setCreater(myuser.getUserName());
		customerBean.setCreationTime(dateString);
		int sortKey = basicDataMapper.getMaxSort() + 1;// 序号 不知道干嘛用
		customerBean.setSortKey(sortKey);
		customerBean.setCompany(myuser.getCompany());
		basicDataMapper.insertCustomer(customerBean);
	}
	
	// 插入客户信息子公司
	public void insertCustomerSub(CustomerBean customerBean, MyUser myuser) throws ServiceException {
		Map<String, String> map = new HashMap<String, String>();
		map.put("loginCompany", myuser.getCompany());
		map.put("customerCode", customerBean.getCustomerCode());
		map.put("customerName", customerBean.getCustomerName());
		map.put("id", customerBean.getId());
		List<CustomerBean> list = basicDataMapper.compareCustomerSub(map);
		if (list != null && list.size() > 0) {
			throw new ServiceException(ReturnStringUtil.CUSTOMER_ALERADY_HAVE_ECEPTION);
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String dateString = sdf.format(new Date());
		customerBean.setCreater(myuser.getUserName());
		customerBean.setCreationTime(dateString);
		//int sortKey = basicDataMapper.getMaxSort() + 1;// 序号 不知道干嘛用
		//customerBean.setSortKey(sortKey);
		customerBean.setCompany(myuser.getCompany());
		basicDataMapper.insertCustomerSub(customerBean);
	}

	// 查询所有工序
	public DatatablesViewPageBean<ProcessBean> queryProcess(Map map) throws ServiceException {
		int count = 0;
		String[] searchText = map.get("searchText") == null ? null : map.get("searchText").toString().split("\\s+");
		map.put("searchText", searchText);
		DatatablesViewPageBean<ProcessBean> dtcpb = new DatatablesViewPageBean<ProcessBean>();
		count = basicDataMapper.queryProcessCount(map);
		dtcpb.setReturnData(basicDataMapper.queryProcess(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	// public List<ProcessBean> queryProcess() {
	// List<ProcessBean> queryProcess = basicDataMapper.queryProcess();
	// return queryProcess;
	// }
	// 查询所有周期
	public DatatablesViewPageBean<WorkshopProductionCycleBean> queryCycle(Map map) throws ServiceException {
		int count = 0;
		DatatablesViewPageBean<WorkshopProductionCycleBean> dtcpb = new DatatablesViewPageBean<WorkshopProductionCycleBean>();
		count = basicDataMapper.queryCycleCount(map);
		dtcpb.setReturnData(basicDataMapper.queryCycle(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	// 获取车间名称
	public List<WorkshopProductionCycleBean> getWorkshopName(Map map) {
		return basicDataMapper.getWorkshopName(map);
	}

	/**
	 * 
	 * Title: getWorkshopNameByDeptId Description: 通过部门id获取车间信息
	 * 
	 * @param map
	 * @return
	 * @author 王荣
	 * @date 2018年4月7日 下午6:44:17
	 */
	public List<WorkshopProductionCycleBean> getWorkshopNameByDeptId(Map map) {
		return basicDataMapper.getWorkshopNameByDeptId(map);
	}

	public List<String> getWorkingProcedureName(Map map) {
		return basicDataMapper.getWorkingProcedureName(map);
	}

	/**
	 * 获取中文字符串首字母 返回首字母
	 * @param str 要转换的中文字符串
	 * @param bUpCase 是否大写
	 * @return
	 */
	public static String getPYIndexStr(String str, boolean bUpCase) {
		StringBuilder convert = new StringBuilder();
		for (int j = 0; j < str.length(); j++) {
			char word = str.charAt(j);
			String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
			if (pinyinArray != null) {
				convert.append(pinyinArray[0].charAt(0));
			} else {
				convert.append(word);
			}
		}
		/* 转换为大写 */
		if(bUpCase) {
			return convert.toString().toUpperCase();
		}
		//默认小写
		return convert.toString();
	}

	/**
	 * 获取车间信息
	 * @author nateLu
	 * @param map
	 * @return
	 */
	public List<WorkshopProductionCycleBean> getWorkshop(Map map) {
		return basicDataMapper.getWorkshop(map);
	}

	/**
	 * 根据车间id查找工序
	 * @author nateLu
	 * @param map
	 * @return
	 */
	public List<ProcessBean> getWorkingProcedureByWorkId(Map map) {
		return basicDataMapper.getWorkingProcedureByWorkId(map);
	}

	/**
	 * 通过车间名称找到车间信息
	 * 
	 * @author natelu
	 * @param workShopName
	 * @return
	 */
	public WorkshopProductionCycleBean getWorkShopByName(Map map) {
		return basicDataMapper.getWorkShopByName(map);
	}

	/**
	 * 根据id查找工序信息
	 * 
	 * @author natelu
	 * @param procedurId
	 * @return
	 */
	public ProcessBean getProcessById(String procedurId) {
		// TODO Auto-generated method stub
		return basicDataMapper.getProcessById(procedurId);
	}

	/**
	 * 根据id获取车间信息
	 * 
	 * @author nateLu
	 * @param workShopId
	 * @return
	 */
	public WorkshopProductionCycleBean getWCById(String workShopId) {
		return basicDataMapper.getWCById(workShopId);
	}

	/**
	 * 根据车间id和工序名称查找id
	 * 
	 * @author natelu
	 * @param workShopId
	 * @return
	 */
	public ProcessBean getProcessByWorkShopId(String workShopId) {
		String proce = "交接入库";
		return basicDataMapper.getProcessByWorkShopId(workShopId, proce);
	}

	/**
	 * @author natelu 获取所有车间下的所有工序
	 * @param map
	 * @return
	 */
	public List<WorkshopProductionCycleBean> getAllWorkShopAndProcedure(Map map) {
		List<WorkshopProductionCycleBean> xx = new ArrayList<WorkshopProductionCycleBean>();
		List<ProcessBean> procedureList = new ArrayList<ProcessBean>();
		int type = Integer.parseInt(map.get("type").toString());
		// 设置用户工序
		if (type == 1) {
			map.put("loginUserId", map.get("userId"));
			procedureList = orderProcedureTemplateService.getUserProcedureByUserId(map);
		}
		// 添加订单工序
		if (type == 2) {
			procedureList = orderProcedureTemplateService.getOrderProcess(map);
		}
		if (type == 3) {
			procedureList = orderProcedureTemplateService.getTemolateProcess(map);
		}
		map.put("procedureList", procedureList);
		xx = basicDataMapper.getAllWorkShopAndProcedure(map);
		return xx;
	}

	/**
	 * 获取订单物料信息
	 * 
	 * @author natelu
	 * @param map
	 * @return
	 */
	public DatatablesViewPageBean getOrderMaterial(Map map) {
		// 查询订单有没有生成过投料单，具现再你那就是d.order is not null
		FeedOrderMainBean feedOrderMainBean = orderService.getFeedOrderMainByOrderId(map);
		if (null != feedOrderMainBean) {
			map.put("isQuery", 0);
		}
		int count = 0;
		DatatablesViewPageBean<CompanyMaterialTableBean> dtcpb = new DatatablesViewPageBean<CompanyMaterialTableBean>();
		count = basicDataMapper.getOrderMaterialCount(map);
		dtcpb.setReturnData(basicDataMapper.getOrderMaterial(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	/**
	 * 用于补全公司物料表信息 保存公司物料表和订单明细表 at 2018-03-30 by 李斌
	 * 
	 * @param materialBean
	 * @param myUser
	 * @throws ServiceException
	 * @throws IOException 
	 */
	@SuppressWarnings("unchecked")
	public void updateBasicDataAndOrderInfoDetail(Map map, MyUser myUser) throws ServiceException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String dateString = sdf.format(new Date());
		// 物料代码
		String materialCode = null;
		// 物料表引用
		CompanyMaterialTableBean companyMaterial = null;
		// 先从公司物料表中查询一次是否有相同的数据,再判断是否插入
		map.put("loginCompany", myUser.getCompany());
		Map<String, Object> unique = new HashMap<String, Object>();
		// 订单明细表id
		Assert.notNull(map.get("orderId"), "订单id为空异常");
		int orderId = Integer.parseInt(map.get("orderId").toString());
		// 更新订单明细表
		OrderInfoDetailBean orderInfoDetail = orderService.getOrderInfoDetailById(orderId);
		OrderInfoDetailBean copeOrder = new OrderInfoDetailBean();
		BeanUtils.copyProperties(orderInfoDetail, copeOrder);
		// 校验该物料类型是否需要用颜色来标识为统一物料
		int isReadColor = orderInfoDetail.getIsReadColor();
		if(isReadColor==0) {
			Map<String, String> mateiralTypeMap = new HashMap<String, String>();
			mateiralTypeMap.put("loginCompany", myUser.getCompany());
			mateiralTypeMap.put("materialType", map.get("materialType").toString());
			CompanyMaterialTypeBean materialTreeBean = companyMaterialTypeService
					.getCompanyMaterialTypeByMateiralType(mateiralTypeMap);
			// 1是读取物料颜色
			if (materialTreeBean != null) {
				isReadColor = materialTreeBean.getIsReadColor();
			}
		}
		//不区分读颜色
		unique.put("color", map.get("color").toString().trim());
		unique.put("materialName", map.get("materialName").toString().trim());
		unique.put("model", map.get("model").toString().trim());
		unique.put("providerName", map.get("providerName").toString().trim());
		unique.put("loginCompany", map.get("loginCompany"));
		unique.put("materialDeptId", map.get("materialDeptId"));
		/*if (isReadColor == 1) {
			unique.put("color", map.get("color").toString().trim());
			unique.put("materialName", map.get("materialName").toString().trim());
			unique.put("model", map.get("model").toString().trim());
			unique.put("providerName", map.get("providerName").toString().trim());
			unique.put("loginCompany", map.get("loginCompany"));
		} else {
			unique.put("materialName", map.get("materialName").toString().trim());
			unique.put("model", map.get("model").toString().trim());
			unique.put("providerName", map.get("providerName").toString().trim());
			unique.put("loginCompany", map.get("loginCompany").toString().trim());
			unique.put("color", "");
		}*/
		List<CompanyMaterialTableBean> companyMaterialList = basicDataMapper.getUniqueCompanyMaterialByDetail(unique);
		// 若查到有相同的物料
		if (companyMaterialList != null && companyMaterialList.size() > 0) {
			companyMaterial = companyMaterialList.get(0);
			materialCode = companyMaterial.getMaterialCode();
			Assert.notNull(companyMaterial.getMaterialCode(), "物料代码为空异常");
			// 如果物料类型读取颜色,原物料没有颜色描述,而订单有颜色描述,那么就把订单的颜色描述赋值给物料
			if (isReadColor == 1 && (companyMaterial.getColorDescription() == null
					|| companyMaterial.getColorDescription().equals(""))) {
				String colorDesc = (String) map.get("colorDescription");
				if (colorDesc != null && !colorDesc.trim().equals("")) {
					companyMaterial.setColorDescription(colorDesc);
					basicDataMapper.updateCompanyMaterial(companyMaterial);
				}
			}
		} else {
			companyMaterial = new CompanyMaterialTableBean();
			companyMaterial.setDefaultWarehouse(
					map.get("defaultWarehouse") != null ? map.get("defaultWarehouse").toString() : "");
			//不区分是否读颜色
			companyMaterial.setColor(map.get("color") != null ? map.get("color").toString() : "");
			companyMaterial.setColorDescription(
					map.get("colorDescription") != null ? map.get("colorDescription").toString() : "");
			/*if (isReadColor == 1) {
				companyMaterial.setColor(map.get("color") != null ? map.get("color").toString() : "");
				companyMaterial.setColorDescription(
						map.get("colorDescription") != null ? map.get("colorDescription").toString() : "");
			}else {
				companyMaterial.setColor("");
				companyMaterial.setColorDescription("");
			}*/
			companyMaterial.setMaterialName(map.get("materialName") != null ? map.get("materialName").toString() : "");
			companyMaterial.setModel(map.get("model") != null ? map.get("model").toString() : "");
			companyMaterial.setUnit(map.get("unit") != null ? map.get("unit").toString() : "");
			companyMaterial.setUnitPrice(
					Double.parseDouble(map.get("unitPrice") != "" ? map.get("unitPrice").toString() : "0"));
			companyMaterial
					.setIsEquals(Integer.parseInt(map.get("isEquals") != null ? map.get("isEquals").toString() : "0"));
			companyMaterial.setStatus(map.get("status") != null ? map.get("status").toString() : "");
			companyMaterial.setProviderName(map.get("providerName") != null ? map.get("providerName").toString() : "");
			companyMaterial.setMaterialType(map.get("materialType") != null ? map.get("materialType").toString() : "");
			companyMaterial.setProcurementCycles(Integer
					.parseInt(map.get("procurementCycles") != "" ? map.get("procurementCycles").toString() : "0"));
			companyMaterial.setLastModifyTime(dateString);
			companyMaterial.setLastModifier(myUser.getUserName());
			companyMaterial.setCompany(myUser.getCompany());
			companyMaterial.setCreater(myUser.getUserName());
			companyMaterial.setCreationTime(dateString);
			companyMaterial.setMaterial(map.get("material") != null ? map.get("material").toString() : "");
			if (map.get("transmittance") == null || map.get("transmittance").equals("")) {
				companyMaterial.setTransmittance(null);
			} else {
				companyMaterial.setTransmittance(Double.valueOf(map.get("transmittance").toString()));
			}
			if (map.get("safetyStockMax") != null) {
				companyMaterial.setSafetyStockMax(Double.valueOf(map.get("safetyStockMax").toString()));
			}
			if (map.get("safetyStockMin") != null) {
				companyMaterial.setSafetyStockMin(Double.valueOf(map.get("safetyStockMin").toString()));
			}
			if (map.get("materialDeptId") != null) {
				companyMaterial.setMaterialDeptId(Integer.parseInt(map.get("materialDeptId").toString()));
			}
			materialCode = this.setCompanyMaterialCode(companyMaterial.getProviderName(),
					companyMaterial.getMaterialName());
			companyMaterial.setMaterialCode(materialCode);
			basicDataMapper.insertCompanyMaterialDetail(companyMaterial);
			map.put("companyMaterialTableBean", companyMaterial);
			this.addCompanyMaterialCountOnMaterial(map);
		}
		if(isReadColor == 1) {
			orderInfoDetail.setColor(companyMaterial.getColor());
			//orderInfoDetail.setColorDescription(companyMaterial.getColorDescription());
		}
		orderInfoDetail.setLineNo(orderInfoDetail.getSequeueNo());
		orderInfoDetail.setMaterialModel(companyMaterial.getModel());
		orderInfoDetail.setMaterialCode(materialCode);
		Assert.isTrue(orderInfoDetail.getMaterialCode() != null && !orderInfoDetail.getMaterialCode().trim().equals(""),
				"订单物料代码为空异常");
		if (orderInfoDetail.getSequeueNo().trim().equals("-1")) {
			Map<String, Object> orderMap = new HashMap<String, Object>();
			orderMap.put("orderNo", orderInfoDetail.getOrderNo());
			orderMap.put("materialType", orderInfoDetail.getMaterialType());
			orderMap.put("materialFatory", orderInfoDetail.getMaterialFactory());
			List<OrderInfoDetailBean> orderInfoDetailBeans = orderMapper.getOrderInfoTailByOrderDetail(orderMap);
			if (orderInfoDetailBeans != null && orderInfoDetailBeans.size() > 0) {
				OrderInfoDetailBean orderInfoTail = orderInfoDetailBeans.get(0);
				orderInfoTail.setMaterialModel(orderInfoDetail.getMaterialModel());
				if(isReadColor == 1) {
					orderInfoTail.setColor(orderInfoDetail.getColor());
					orderInfoTail.setColorDescription(orderInfoDetail.getColorDescription());
				}
				orderInfoTail.setMaterialCode(orderInfoDetail.getMaterialCode());
				orderMapper.updateOrderInfoTailById(orderInfoTail);
			}
		}
		int row = basicDataMapper.updateOrderInfoDetailByCompanyMaterialCode(orderInfoDetail);
		Assert.isTrue(row > 0, "补全订单失败");
		//如果校验通过了.那么就删除备份审核记录
//		duplicateOrderUpdateRecordsMapper.deleteDuplicateOrderByOrder(orderInfoDetail);
	}

	/**
	 * 插入公司物料表和出入库表 at 2018-04-01 by 李斌
	 * 调用此接口的方法没有再使用  作废
	 * @param map
	 */
	public void insertCompanyMaterialAndWarehouse(Map map) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		// 物料bean
		CompanyMaterialTableBean companyMaterial = null;
		// 物料代码
		String materialCode = null;
		// 查询公司物料表中是否有相同的物料数据.不用物料代码查
		List<CompanyMaterialTableBean> companyMaterialList = basicDataMapper.getUniqueCompanyMaterialByDetail(map);
		// 判断公司物料表中是否已经有了此物料信息,如果没有就插入
		if (companyMaterialList != null && companyMaterialList.size() > 0) {
			for (int i = 0; i < companyMaterialList.size(); i++) {
				companyMaterial = companyMaterialList.get(i);
				if (!"".equals(companyMaterial.getMaterialCode().replace(" ", ""))) {
					materialCode = companyMaterial.getMaterialCode();
					break;
				} else {
					materialCode = this.setCompanyMaterialCode(companyMaterial.getProviderName(),
							companyMaterial.getMaterialName());
				}
			}
			companyMaterial.setLastModifier(map.get("loginUserName").toString());
			companyMaterial.setLastModifyTime(sdf.format(new Date()));
			companyMaterial.setMaterialCode(materialCode);
			Double oldCount = companyMaterial.getCount();
			if (oldCount == null || "".equals(oldCount.toString().replace(" ", ""))) {
				oldCount = 0.0;
			}
			Double newCount = Double.valueOf(map.get("count").toString());
			companyMaterial.setCount(oldCount + newCount);
			companyMaterialList.clear();
			companyMaterialList.add(companyMaterial);
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("listCompanyMaterial", companyMaterialList);
			paramMap.put("loginCompany", map.get("loginCompany"));
			companyMaterialMapper.updateCompanyMaterialTableOnCountAndTime(paramMap);
		} else {
			companyMaterial = new CompanyMaterialTableBean();
			companyMaterial.setMaterialName(map.get("materialName").toString());
			companyMaterial.setMaterialType(map.get("materialType").toString());
			companyMaterial.setStatus(map.get("status").toString());
			companyMaterial.setModel(map.get("model").toString());
			companyMaterial.setUnit(map.get("unit").toString());
			companyMaterial.setUnitPrice(Double.valueOf(map.get("unitPrice").toString()));
			companyMaterial.setColor(map.get("color").toString());
			companyMaterial.setColorDescription(map.get("colorDescription").toString());
			companyMaterial.setCompany(map.get("loginCompany").toString());
			companyMaterial.setCreater(map.get("loginUserName").toString());
			companyMaterial.setCreationTime(sdf.format(new Date()));
			companyMaterial.setLastModifier(map.get("loginUserName").toString());
			companyMaterial.setLastModifyTime(sdf.format(new Date()));
			companyMaterial.setDefaultWarehouse(map.get("defaultWarehouse").toString());
			companyMaterial.setIsEquals(Integer.valueOf(map.get("isEquals").toString()));
			companyMaterial.setProviderName(map.get("providerName").toString());
			companyMaterial.setProcurementCycles(Integer.valueOf(map.get("procurementCycles").toString()));
			companyMaterial.setCount(Double.valueOf(map.get("count").toString()));
			materialCode = this.setCompanyMaterialCode(companyMaterial.getProviderName(),
					companyMaterial.getMaterialName());
			companyMaterial.setMaterialCode(materialCode);
			basicDataMapper.insertCompanyMaterialDetail(companyMaterial);
		}

		// 添加入库明细表
		WarehouseInOutDetailBean warehouseInDetail = new WarehouseInOutDetailBean();
		String rkId = dingTalkMapper.getApprovalNo("RK");
		warehouseInDetail.setId(rkId);
		warehouseInDetail.setType(1);
		warehouseInDetail.setCount(companyMaterial.getCount());
		warehouseInDetail.setMaterialCode(companyMaterial.getMaterialCode());
		warehouseInDetail.setMaterialName(companyMaterial.getMaterialName());
		warehouseInDetail.setPurcharseOrderId("无采购单入库");
		warehouseInDetail.setCompany(companyMaterial.getCompany());
		warehouseInDetail.setStatus(1);
		warehouseInDetail.setApprovalTime(companyMaterial.getCreationTime());
		warehouseInDetail.setApprovalUser(map.get("loginUserId").toString());
		warehouseInDetail.setCreateTime(companyMaterial.getCreationTime());
		warehouseInDetail.setCreateUser(map.get("loginUserId").toString());
		WarehouseInOutDetailBean oldWarehouseInDetailBean = companyMaterialMapper
				.getInWarehourseByIdOne(warehouseInDetail.getId());
		if (oldWarehouseInDetailBean == null) { // 如果仓库表中没有相同的数据那么就插入
			List<WarehouseInOutDetailBean> warehouseInDetailList = new ArrayList<WarehouseInOutDetailBean>();
			warehouseInDetailList.add(warehouseInDetail);
			warehouseService.checkTakingIsNotApproval(warehouseInDetailList, map.get("loginCompany").toString());
			companyMaterialMapper.insertInOutRecode(warehouseInDetailList);
		}

	}

	/**
	 * @Title: getCompanyMaterialNameByCount @Description: 用于领料单
	 *         获取物料名称通过公司物料表中正在使用的并且库存数量不为零的 @date 2018年4月4日 上午8:30:53 @author
	 *         李斌 @return Object @throws
	 */
	public List<String> getCompanyMaterialNameByCount(Map map) {
		return basicDataMapper.getCompanyMaterialNameByCount(map);
	}

	/**
	 * 用于领料单 获取物料规格通过公司物料表中正在使用的物料并且库存数量不为零通过物料名称筛选 @date 2018年4月4日
	 * 上午8:53:34 @author 李斌 @return Object @throws
	 */
	public List<String> getModelByCountAndMaterialName(Map map) {
		List<String> modelList = basicDataMapper.getModelByCountAndMaterialName(map);

		if (modelList != null && modelList.size() > 0) {
			// 利用set的特性去重复
			Set<String> sets = new HashSet<String>(modelList);
			// 清楚
			modelList.clear();
			modelList.addAll(sets);
		}
		return modelList;
	}

	/**
	 * 用于领料单 获取物料的默认仓库通过公司物料表中正在使用的物料并且库存数量不为零通过物料名称筛选 @date 2018年4月4日
	 * 上午9:25:13 @author 李斌 @return List @throws
	 */
	public List<String> getDefaultWarehouseByCountAndMaterialName(Map map) {
		// TODO Auto-generated method stub
		List<String> defaultWarehouseList = basicDataMapper.getDefaultWarehouseByCountAndMaterialName(map);
		if (defaultWarehouseList != null && defaultWarehouseList.size() > 0) {
			Set<String> sets = new HashSet<String>(defaultWarehouseList);
			defaultWarehouseList.clear();
			defaultWarehouseList.addAll(sets);
		}
		return defaultWarehouseList;
	}

	/**
	 * 用于领料单 获取物料的供应商名称通过公司物料表中正在使用的物料并且库存数量不为零通过物料名称筛选 @date 2018年4月4日
	 * 上午9:43:24 @author 李斌 @return List @throws
	 */
	public List<String> getProviderNameByCountAndMaterialName(Map map) {
		// TODO Auto-generated method stub
		List<String> providerList = basicDataMapper.getProviderNameByCountAndMaterialName(map);
		if (providerList != null && providerList.size() > 0) {
			Set<String> sets = new HashSet<String>(providerList);
			providerList.clear();
			providerList.addAll(sets);
		}
		return providerList;
	}

	/**
	 * 用于领料单 获取物料的物料类型通过公司物料表中正在使用的物料并且库存数量不为零通过物料名称筛选 @date 2018年4月4日
	 * 上午9:56:42 @author 李斌 @return List<String> @throws
	 */
	public List<String> getMaterialTypeByCountAndMaterialName(Map map) {
		// TODO Auto-generated method stub
		List<String> materialTypeList = basicDataMapper.getMateialTypeByCountAndMaterialName(map);
		if (materialTypeList != null && materialTypeList.size() > 0) {
			Set<String> sets = new HashSet<String>(materialTypeList);
			materialTypeList.clear();
			materialTypeList.addAll(sets);
		}
		return materialTypeList;
	}

	/**
	 * 用于领料单 获取物料的色号通过公司物料表中正在使用的物料并且库存数量不为零通过物料名称筛选 @date 2018年4月4日
	 * 上午10:12:01 @author 李斌 @return List @throws
	 */
	public List<String> getColorByCountAndMaterialName(Map map) {
		// TODO Auto-generated method stub
		List<String> colorList = basicDataMapper.getColorByCountAndMaterialName(map);
		if (colorList != null && colorList.size() > 0) {
			Set<String> sets = new HashSet<String>(colorList);
			colorList.clear();
			colorList.addAll(sets);
		}
		return colorList;
	}

	/**
	 * 获取剩余可领取的库存数 @date 2018年4月4日 上午10:52:30 @author 李斌 @return List @throws
	 */
	public List<CompanyMaterialTableBean> getSurplusAmount(Map map) {
		// TODO Auto-generated method stub
		return basicDataMapper.getSurplusAmount(map);
	}

	/**
	 * Title: getDeptId2 Description: 通过部门名称，获取对应部门的车间信息
	 * 
	 * @param map
	 * @return
	 * @author 王荣
	 * @date 2018年4月8日 下午4:47:29
	 */
	public List<WorkshopProductionCycleBean> getDeptId2(Map map) {
		return basicDataMapper.getDeptId2(map);
	}

	/**
	 * @author nateLu 获取生产部门信息
	 * @param map
	 * @return
	 */
	public List<DepartmentBean> getProductionDepartment(Map map) {
		return basicDataMapper.getProductionDepartment(map);
	}

	/**
	 * Title: getRowMaterialType Description: 获取公共的物料类型
	 * 
	 * @param map
	 * @return
	 * @author 王荣
	 * @date 2018年4月16日 上午11:33:44
	 */
	public List<String> getRowMaterialType(Map map) {
		// return basicDataMapper.getRowMaterialType(map);
		// 获取公共物料类型+公司自己添加的物料类型
		return companyMaterialTypeService.getCompanyMaterialTypeList(map);
	}

	/**
	 * Title: getRowMaterialTypeIincludeAccessories Description:包含辅料的所有物料
	 * 
	 * @param map
	 * @return
	 * @author nate
	 * @date 2018年4月16日 上午11:33:44
	 */
//	public List<String> getRowMaterialTypeIincludeAccessories(Map map) {
//		List<String> list=basicDataMapper.getRowMaterialTypeIincludeAccessories(map);
//		List<String> returnList=list.stream().distinct().collect(Collectors.toList());
//		return returnList;
//	}

	/**
	 * 通过物料的信息获取物料 @date 2018年4月18日 下午1:35:24 @author 李斌 @return Object @throws
	 */
	public List<CompanyMaterialTableBean> getCompanyMaterialByDetail(Map map) {
		// TODO Auto-generated method stub
		return basicDataMapper.getCompanyMaterialByDetail(map);
	}

	/**
	 * @throws ServiceException
	 *             更新订单明细表,通过物料代码 @date 2018年4月19日 下午3:23:49 @author 李斌 @return
	 *             Object @throws
	 */
	public int updateOrderInfoDetailByCompanyMaterialCode(Map map) throws ServiceException {
		// TODO Auto-generated method stub
		List<CompanyMaterialTableBean> lists = basicDataMapper.getCompanyMaterialByDetail(map);
		CompanyMaterialTableBean material = null;
		for (CompanyMaterialTableBean companyMaterial : lists) {
			material = companyMaterial;
			if (material != null) {
				break;
			}
		}
		if (material == null) {
			return 0;
		}
		if (map.get("id") == null) {
			return 0;
		}
		Assert.isTrue(material.getMaterialCode() != null && !"".equals(material.getMaterialCode().trim()), "物料代码为空");
		OrderInfoDetailBean orderInfoDetail = orderService
				.getOrderInfoDetailById(Integer.parseInt(map.get("id").toString()));
		orderInfoDetail.setMaterialCode(material.getMaterialCode());
		orderInfoDetail.setMaterialModel(material.getModel());
		int isReadColor = orderInfoDetail.getIsReadColor();
		if(isReadColor==0) {
			Map<String, String> mateiralTypeMap = new HashMap<String, String>();
			mateiralTypeMap.put("loginCompany", map.get("loginCompany").toString());
			mateiralTypeMap.put("materialType", orderInfoDetail.getMaterialType());
			CompanyMaterialTypeBean materialTreeBean = companyMaterialTypeService
					.getCompanyMaterialTypeByMateiralType(mateiralTypeMap);
			// 1是读取物料颜色
			if (materialTreeBean != null) {
				isReadColor = materialTreeBean.getIsReadColor();
			}
		}
		if(isReadColor==1) {
			// 如果物料类型读取颜色,原物料没有颜色描述,而订单有颜色描述,那么就把订单的颜色描述赋值给物料
			if (material.getColorDescription() == null || material.getColorDescription().equals("")) {
				String colorDesc = orderInfoDetail.getColorDescription();
				if (colorDesc != null && !colorDesc.trim().equals("")) {
					material.setColorDescription(colorDesc);
					basicDataMapper.updateCompanyMaterial(material);
				}
			}
			orderInfoDetail.setColor(material.getColor());
			//依旧使用订单的颜色描述
			//orderInfoDetail.setColorDescription(material.getColorDescription());
		}
		if (orderInfoDetail.getMaterialCode() == null || orderInfoDetail.getMaterialCode().trim().equals("")) {
			throw new ServiceException("订单物料代码为空异常");
		}
		if (orderInfoDetail.getSequeueNo() == null || orderInfoDetail.getSequeueNo().trim().equals("")) {
			throw new ServiceException("订单明细序号为空异常");
		}
		if (orderInfoDetail.getSequeueNo().trim().equals("-1")) {
			Map<String, Object> orderMap = new HashMap<String, Object>();
			orderMap.put("orderNo", orderInfoDetail.getOrderNo());
			orderMap.put("materialType", orderInfoDetail.getMaterialType());
			orderMap.put("materialFatory", orderInfoDetail.getMaterialFactory());
			List<OrderInfoDetailBean> orderInfoDetailBeans = orderMapper.getOrderInfoTailByOrderDetail(orderMap);
			if (orderInfoDetailBeans != null && orderInfoDetailBeans.size() > 0) {
				OrderInfoDetailBean orderInfoTail = orderInfoDetailBeans.get(0);
				orderInfoTail.setMaterialModel(orderInfoDetail.getMaterialModel());
				if(isReadColor==1) {
					orderInfoTail.setColorDescription(orderInfoDetail.getColorDescription());
					orderInfoTail.setColor(orderInfoDetail.getColor());
				}
				orderInfoTail.setMaterialCode(orderInfoDetail.getMaterialCode());
				orderMapper.updateOrderInfoTailById(orderInfoTail);
			}
		}
		int row = basicDataMapper.updateOrderInfoDetailByCompanyMaterialCode(orderInfoDetail);
		//如果校验通过了.那么就删除备份审核记录
//		duplicateOrderUpdateRecordsMapper.deleteDuplicateOrderByOrder(orderInfoDetail);
		return row;
	}

	/**
	 * 
	 * Title: getAdminDept Description: 获取admin公司的部门信息,用于导入
	 * 
	 * @param map
	 * @return
	 * @author 王荣
	 * @date 2018年4月24日 下午3:00:14
	 */
	public List<DepartmentBean> getAdminDept(Map map) {
		return basicDataMapper.getProductionDepartment(map);
	}

	/**
	 * Title: importDept Description: 导入部门
	 * 
	 * @param map
	 * @return
	 * @author 王荣
	 * @date 2018年4月25日 上午8:38:59
	 */
	public void importDept(Map map) {
		basicDataMapper.importDept(map);
	}

	/**
	 * Title: importWorkshop Description: 导入车间
	 * 
	 * @param map
	 * @author 王荣
	 * @date 2018年4月25日 下午7:48:08
	 */
	public void importWorkshop(Map map) {
		Assert.isTrue(map.get("workshopStr") != null && !"".equals(map.get("workshopStr").toString()), "未获取到导入车间id");
		String workshopStr = map.get("workshopStr").toString();
		String [] workShopIdArray=workshopStr.split(",");
		for(int i=0;i<workShopIdArray.length;i++) {
			WorkshopProductionCycleBean worl = this.getWCById(workShopIdArray[i]);
			Assert.notNull(worl, "导入车间不存在");
			DepartmentBean departmentBean = basicDataMapper.checkDeptHave(worl.getProductionLine(),
					map.get("loginCompany").toString());
			if (departmentBean != null) {
				map.put("deptId", departmentBean.getId());
			} else {
				basicDataMapper.importWorkshopDept(map);
			}
			map.put("workshopName", worl.getWorkshopName());
			map.put("workShopId", workShopIdArray[i]);
			List<WorkshopProductionCycleBean> list = basicDataMapper.checkWorkshopIsRepeat(map);
			Assert.isTrue(list == null || list.size() <= 0,worl.getWorkshopName()+ "车间已存在");
			basicDataMapper.importWorkshop(map);
			// 插入工序：交接出入库
			basicDataMapper.insertHandoverProcess(map);
		}
	}

	/**
	 * Title: getAdminProcess Description: 获取admin的工序
	 * 
	 * @param map
	 * @return
	 * @author 王荣
	 * @date 2018年4月26日 下午2:24:06
	 */
	public List<ProcessBean> getAdminProcess(Map map) {
		long start = System.currentTimeMillis();
		String searchText = map.get("searchText").toString();
		System.out.println("searchText:" + searchText);
		List<ProcessBean> list = basicDataMapper.getAdminProcess(map);
		long end = System.currentTimeMillis();
		System.out.println("getAdminProcess花费时间：" + (end - start) + "ms");
		return list;

	}

	/**
	 * Title: importprocess Description: 导入工序
	 * 
	 * @param map
	 * @author 王荣
	 * @date 2018年4月27日 上午10:37:07
	 */
	public void importprocess(Map map) {
		basicDataMapper.importprocess(map);
	}

	/**
	 * Title: getWorkshopName2 Description: TODO(这里用一句话描述这个方法的作用)
	 * 
	 * @param map
	 * @return
	 * @author 王荣
	 * @date 2018年4月30日 下午5:19:27
	 */
	public List<WorkshopProductionCycleBean> getWorkshopName2(Map map) {
		return basicDataMapper.getWorkshopName2(map);
	}

	/**
	 * 获取有效的供应商名称 @date 2018年5月9日 下午3:54:11 @author 李斌 @return Object @throws
	 */
	public List<String> getValidProviderName(Map map) {
		// TODO Auto-generated method stub
		return basicDataMapper.getValidProviderName(map);
	}

	/**
	 * Title: getPhoneNumber Description: 获取公司手机号
	 * 用于判断此手机号是否被使用（使用手机号登录时同一公司有两个相同的手机号会产生异常）
	 * 
	 * @param map
	 * @return List<String>
	 * @author 王荣
	 * @date 2018年5月17日 下午3:48:52
	 */
	public List<String> getPhoneNumber(Map map) {
		return basicDataMapper.getPhoneNumber(map);
	}

	/**
	 * Title: getDuty Description: 获取职务
	 * 
	 * @param map
	 * @return
	 * @author 王荣
	 * @date 2018年5月23日 上午11:03:13
	 */
	public List<String> getDuty(Map map) {
		return basicDataMapper.getDuty(map);
	}

	/**
	 * Title: getMaterialInfo Description: TODO(这里用一句话描述这个方法的作用)
	 * 
	 * @param map
	 * @return
	 * @author 王荣
	 * @date 2018年5月23日 下午4:49:46
	 */
	public CompanyMaterialTableBean getMaterialInfo(Map map) {
		return basicDataMapper.getMaterialInfo(map);
	}

	/**
	 * 获取车间分页数据
	 * 
	 * @author natelu
	 * @param deptId(部门id
	 *            非必传)
	 * @param workShopId(车间id
	 *            非必传)
	 * @param selectWhere(模糊查车间名称)
	 * @return
	 * @throws ServiceException
	 */
	public DatatablesViewPageBean getWorkShopPage(Map map) {
		int count = 0;
		DatatablesViewPageBean<WorkshopProductionCycleBean> dtcpb = new DatatablesViewPageBean<WorkshopProductionCycleBean>();
		count = basicDataMapper.getWorkShopPageCount(map);
		dtcpb.setReturnData(basicDataMapper.getWorkShopPageData(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	/**
	 * 获取公司所有人员
	 * 
	 * @author nate
	 * @param request
	 * @return
	 * @throws ServiceException
	 */
	public DatatablesViewPageBean getUser(Map map) {
		int count = 0;
		DatatablesViewPageBean<UserBean> dtcpb = new DatatablesViewPageBean<UserBean>();
		count = basicDataMapper.getUserCount(map);
		dtcpb.setReturnData(basicDataMapper.getUserData(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	/**
	 * 获取车间报报工审核人员
	 * 
	 * @param workShopId
	 * @param type(1 报工 2 外协)
	 * @return
	 * @throws ServiceException
	 * @author nate
	 */
	public List<String> getWorkShopApprovalReportUser(Map map) {
		return basicDataMapper.getWorkShopApprovalReportUser(map);
	}
	
	

	/**
	 * 设置车间审核人员
	 * 
	 * @param workShopId
	 * @param userId
	 * @return
	 * @throws ServiceException
	 * @author nate
	 */
	public void setWorkShopApprovalReportUser(Map map) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
		String dateString = sdf.format(new Date());
		map.put("createTime", dateString);
		map.put("id", StringUtil.getUUID());
		basicDataMapper.deleteByWorkShop(map);
		basicDataMapper.addWorkShopApprovalReportUser(map);
	}
	

	/**
	 * natelu 通过用户id获取用户能审核报工车间
	 * 
	 * @param string
	 * @return
	 */
	public List<String> getUserApprovalReportWorkShopByUserId(String userId) {
		return basicDataMapper.getUserApprovalReportWorkShopByUserId(userId);
	}

	/**
	 * 获取部门下没合并的车间
	 * 
	 * @param deptId
	 * @return
	 * @author nate
	 */
	public List<WorkshopProductionCycleBean> getDeptNoMegerWorkShop(Map map) {
		return basicDataMapper.getDeptNoMegerWorkShop(map);
	}

	/**
	 * 通过客户名称获取客户信息 @date 2018年7月30日 下午4:50:30 @author 李斌 @return
	 * CustomerBean @throws
	 */
	public CustomerBean getCustomerBeanByCustomerName(Map<String, String> map) {
		List<CustomerBean> customerBeans = basicDataMapper.queryCustomers(map);
		return customerBeans.get(0);
	}

	/**
	 * 获取出入库制单人 @date 2018年8月15日 下午2:50:41 @author 李斌 @return List<UserBean> @throws
	 */
	public List<UserBean> getWarehouseInOutCreateUser(Map<String, Object> map) {
		Object warehouse = map.get("warehouse");
		if (warehouse == null) {
			throw new ServiceException("出入库仓位为空异常");
		}
		List<UserBean> userBeans = null;
		// 原材料仓
		if ("1".equals(warehouse.toString())) {
			userBeans = basicDataMapper.getWarehouseInOutCreate(map);
			// 辅料仓
		} else if ("2".equals(warehouse.toString())) {
			userBeans = basicDataMapper.getWarehouseInOutCreate(map);
			// 成品仓
		} else if ("3".equals(warehouse.toString())) {
			userBeans = basicDataMapper.getOtherWarehouseCreate(map);
			// 报废仓
		} else if ("4".equals(warehouse.toString())) {
			userBeans = basicDataMapper.getOtherWarehouseCreate(map);
			// 待处理仓
		} else if ("5".equals(warehouse.toString())) {
			userBeans = basicDataMapper.getOtherWarehouseCreate(map);
		} else {
			return null;
		}
		return userBeans;
	}

	/**
	 * 获取用户通过多部门和多用户
	 * 
	 * @param map
	 * @return
	 * @author 王荣
	 */
	public DatatablesViewPageBean<Map<String, Object>> getUserByDeptIdListAndUserIdList(Map<String, Object> map) {
		map.put("deptIdList", DingTalkUtil.parseJsonArrayStrToListInteger(map.computeIfAbsent("deptIds", k -> "[]").toString()));
        map.put("workshopIdList", DingTalkUtil.parseJsonArrayStrToListInteger(map.computeIfAbsent("workshopIds", k -> "[]").toString()));
        map.put("userIdList", DingTalkUtil.parseJsonArrayStrToListInteger(map.computeIfAbsent("userIds", k -> "[]").toString()));
		int count = 0;
		DatatablesViewPageBean<Map<String, Object>> dtcpb = new DatatablesViewPageBean<Map<String, Object>>();
		count = basicDataMapper.getUserByDeptIdListAndUserIdListCount(map);
		dtcpb.setReturnData(count > 0 ? basicDataMapper.getUserByDeptIdListAndUserIdList(map)
				: new ArrayList<Map<String, Object>>());
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	/**
	 * 是否有库存 @date 2018年9月21日 上午10:23:01 @author 李斌 @return boolean @throws
	 */
	public void isCount(Map<String, Object> paramMap) {
		CompanyMaterialTableBean companyMaterialTableBean = (CompanyMaterialTableBean) paramMap
				.get("companyMaterialTableBean");
		Assert.notNull(companyMaterialTableBean, "物料为空异常");
		paramMap.put("materialCode", companyMaterialTableBean.getMaterialCode());
		CompanyMaterialCountBean companyMaterialCountBean = companyMaterialCountService
				.getCompanyMaterialCountByMaterial(paramMap);
		if (companyMaterialCountBean == null
				|| (companyMaterialCountBean.getCount().equals(0.0) && companyMaterialCountBean.getNoCount().equals(0.0)
						&& companyMaterialCountBean.getProductionUnitNoCount().equals(0.0)
						&& companyMaterialCountBean.getProductionUnitCount().equals(0.0))) {
			paramMap.put("materialCode", companyMaterialTableBean.getMaterialCode());
			List<WarehouseInOutDetailBean> warehouseInOutDetailBeans = companyMaterialMapper
					.getWarehouseInOutByMaterialCodeAndNotStatus(paramMap);
			Assert.isTrue(warehouseInOutDetailBeans == null || warehouseInOutDetailBeans.size() < 1,
					"物料名称 : "+companyMaterialTableBean.getMaterialName()+" 规格 : "+companyMaterialTableBean.getModel()+" 该物料有出入库单未确认,无法禁用");
		} else {
			if (!companyMaterialCountBean.getCount().equals(0.0) || !companyMaterialCountBean.getNoCount().equals(0.0)
					|| !companyMaterialCountBean.getProductionUnitNoCount().equals(0.0)
					|| !companyMaterialCountBean.getProductionUnitCount().equals(0.0)) {
				throw new ServiceException("物料名称 : "+companyMaterialTableBean.getMaterialName()+" 规格 : "+companyMaterialTableBean.getModel()+" 该物料有库存,无法禁用");
			}
		}
	}

	public void checkMaterialIsExist(Map<String, Object> map) {
		List<CompanyMaterialTableBean> companyDatalist = basicDataMapper.getUniqueCompanyMaterialByDetail(map);
		Assert.isTrue(companyDatalist == null || companyDatalist.size() < 1, "该物料已重复,请勿重复添加");
	}
	/**
	 * 通过四要素获取信息(车间交接到半成品时用到)
	 * @author nate
	 * @param map
	 * @return
	 */
	public List<CompanyMaterialTableBean> getUniqueCompanyMaterialByDetail(Map map) {
		return basicDataMapper.getUniqueCompanyMaterialByDetail(map);
	}

	/**
	 * 添加物料库存信息 @date 2018年9月21日 上午10:44:23 @author 李斌 @return void @throws
	 */
	public void addCompanyMaterialCountOnMaterial(Map<String, Object> map) {
		Map<String, Object> unitMaterialMap = new HashMap<String, Object>();
		CompanyMaterialTableBean companyMaterialTableBean = (CompanyMaterialTableBean) map
				.get("companyMaterialTableBean");
		CompanyMaterialCountBean companyMaterialCountBean = new CompanyMaterialCountBean();
		companyMaterialCountBean.setMaterialCode(companyMaterialTableBean.getMaterialCode());
		companyMaterialCountBean.setCount(0.0);
		companyMaterialCountBean.setNoCount(0.0);
		companyMaterialCountBean.setProductionUnitCount(0.0);
		companyMaterialCountBean.setProductionUnitNoCount(0.0);
		Integer warehouseType = null;
		if (companyMaterialTableBean.getDefaultWarehouse().equals("原材料仓")) {
			warehouseType = 4;
		} else if (companyMaterialTableBean.getDefaultWarehouse().equals("辅料仓")) {
			warehouseType = 5;
		}
		if(companyMaterialTableBean.getIsTemplateImport()) {
			companyMaterialCountBean.setCount(companyMaterialTableBean.getCount());
		}
		Assert.notNull(warehouseType, "物料信息仓库为空");
		companyMaterialCountBean.setWarehouseType(warehouseType);
		companyMaterialCountBean.setCompany(map.get("loginCompany").toString());
		unitMaterialMap.put("loginCompany", map.get("loginCompany"));
		unitMaterialMap.put("warehouseType", warehouseType);
		unitMaterialMap.put("materialCode", companyMaterialCountBean.getMaterialCode());
		companyMaterialCountService.duplicateCheck(unitMaterialMap);
		companyMaterialCountService.addCompanyMaterialCount(companyMaterialCountBean);
	}

	public DatatablesViewPageBean<CustomerBean> queryCustomerTows(Map map) {
		int count = 0;
		DatatablesViewPageBean<CustomerBean> dtcpb = new DatatablesViewPageBean<CustomerBean>();
		count = basicDataMapper.queryCustomersTwoCount(map);
		dtcpb.setReturnData(basicDataMapper.queryCustomersTwo(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}
	
	public DatatablesViewPageBean<CustomerBean> queryCustomerSubTows(Map map) {
		int count = 0;
		DatatablesViewPageBean<CustomerBean> dtcpb = new DatatablesViewPageBean<CustomerBean>();
		count = basicDataMapper.queryCustomersTwoSubCount(map);
		dtcpb.setReturnData(basicDataMapper.queryCustomersSubTwo(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}
	
	/**
	 * 获取客户列表
	 * @param map
	 * @return
	 */
	public List<CustomerBean> getCustomerList(Map map){
		return basicDataMapper.queryCustomersTwo(map);
	}
	
	/**
	 * 审核物料
	 * @param map
	 */
	public void approvalCompanyMaterial(CompanyMaterialTableBean materialBean,Map<String, Object> map) {
		int row = basicDataMapper.approvalCompanyMaterial(materialBean);
		Assert.isTrue(row>0, "审核物料失败");
	}

	
	/**
	 * 禁用物料
	 * @param materialBean 
	 * @param map
	 */
	public void disableCompanyMaterial(CompanyMaterialTableBean materialBean,Map<String,String> map) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("companyMaterialTableBean", materialBean);
		paramMap.put("loginCompany", map.get("loginCompany"));
		this.isCount(paramMap);
		int row = basicDataMapper.disableCompanyMaterial(materialBean);
		Assert.isTrue(row>0, "禁用物料失败");
		//物料禁用 删除百度图片
		materialBean.setImg(null);
		materialBean.setImgTwo(null);
		materialBean.setImgThree(null);
		materialBean.setImgFour(null);
		synImgsToBaidu(materialBean, null, null);
	}
	
	/**
	 * 批量禁用物料
	 * @param companyMaterialList
	 * @param map
	 */
	public void disableAllCompanyMaterial(Map<String, String> map) {
		Assert.notNull(map.get("companyMaterialList"),"物料信息为空");
		JSONArray jsonArr = JSONArray.fromObject(map.get("companyMaterialList"));
		List<CompanyMaterialTableBean> companyMaterialList = (List<CompanyMaterialTableBean>) JSONArray.toCollection(jsonArr, CompanyMaterialTableBean.class);
		for(CompanyMaterialTableBean companyMaterialTableBean:companyMaterialList) {
			disableCompanyMaterial(companyMaterialTableBean,map);
		}
	}
}
